<template>
  <div>
    <div class="u-page web">
      <!--    作业页面头部-->
      <homework-header :item="item"
                       :homework="homework"
                       :finished="finished"
                       :stu="stu"
                       :if-write="ifWrite"/>


      <div class="content-container">
        <div class="input-text">
          <el-input
              type="textarea"
              :autosize="{ minRows: 15, maxRows: 20}"
              placeholder="请输入内容"
              v-model="context">
          </el-input>
          <div class="tip">
            <span>还可以输入{{ remainder() }}个字</span>
          </div>
          <div>
            <div class="avatar-container"
                 v-show="file.length > 0"
                 v-for="(item,index) in file">
              <div class="file-attachwarp canPreview"
                   @mouseleave="mouseleave()"
                   @mouseover="mouseover()">
                <div class="file-info">
                  <div class="image-wrap">
                    <div v-show="item.type === 'docx' || item.type === 'doc'"
                         class="file-filetype iconfont icon-word1"></div>
                    <img v-if="item.type === 'jpg' || item.type === 'png' || item.type === 'jpeg'"
                         alt="" :src="`/api/student/download?name=${item.annex}`"/>
                  </div>
                  <div class="file-attachmain">
                    <p class="name">{{ item.name }}</p>
                    <p class="size">{{ item.size }}MB</p>
                  </div>
                  <div class="file-action"
                       :style="cDisplay">
                    <span class="preview" @click="file.splice(index,1)">删除</span>
                  </div>
                </div>

              </div>
            </div>

            <!--                el-upload写在form中会自动提交，导致页面自动刷新-->
            <!--                在form标签中加上@submit.native.prevent-->
            <el-upload
                class="pull-left a"
                action="/api/student/upload"
                ref="upload"
                :show-file-list="false"
                :limit="fileLimit"
                :file-list="fileList"
                :accept="fileType"
                :on-success="handleAvatarSuccess"
                :before-upload="handleBeforeUpload"
                :headers=headers>
              <button class="button">上传附件</button>

            </el-upload>
            <button class="btn button button-red-solid"
                    style="margin-left: 10px"
                    @click="submit">提交
            </button>


          </div>

        </div>
      </div>

    </div>
  </div>
</template>

<script>
import HomeworkHeader from '@/components/headers/HomeworkHeader'
import {obtainFileStuName} from "@/utils/string";
import {homeworkStuSubmit} from "@/apis/student";

export default {
  components: {
    HomeworkHeader,
  },
  props: {},
  data() {
    return {
      item: {},
      homework: {},
      stu: [],
      cDisplay: 'display: none',
      showIframe: false,
      finished: 0,
      ifWrite: false,
      context: "",
      maxLength: 255,
      // 附件列表
      fileList: [],
      // 允许的文件类型
      fileType: 'xls, xlsx, pdf,doc, docx, txt, jpg, png, jpeg',
      // 运行上传文件大小，单位 M
      fileSize: 10,
      // 附件数量限制
      fileLimit: 10,
      headers: {
        token: localStorage.getItem("token"),
      },
      file: [],
    }
  },
  created() {

    this.init()
  },

  methods: {
    async init() {

      this.item = JSON.parse(this.$route.query.item)
      this.homework = JSON.parse(this.$route.query.homework)
      this.stu = JSON.parse(this.$route.query.stu)
      this.ifWrite = this.$route.meta.if_write

      if(JSON.parse(this.$route.query.data !== undefined)){
        let data = JSON.parse(this.$route.query.data)

        this.context = data.data.context
        this.file = data.data.files
      }
    },

    // 提交作业
    submit() {
      console.log(this.stu)
      let submitFile = {
        studentId: localStorage.getItem("id"),
        name: this.stu.name,
        creator: this.stu.creator,
        courseId: this.item.id,
        context: this.context,
        files: this.file,
      }
      homeworkStuSubmit(submitFile).then(resp => {
        if(resp?.data?.code === 1){
          this.$message.success("提交成功")
          this.file = []
          // 跳转至查看作业页面
          this.$router.push({
            name: 'stuHomeworkView',
            query: {
              item: JSON.stringify(this.item),
              stu: JSON.stringify(this.stu),
            }

          }).catch(r => {console.log(r)})


        }else{
          this.$message.error(resp?.data?.msg)
        }

      })


    },


    // 图片上传成功前拦截
    handleAvatarSuccess(res, file) {
      // 处理名字

      // 判断文件名是否重复
      for (let i = 0; i < this.file.length; i++) {
        if (this.file[i].name === this.file.name) {
          this.$message.error("文件不能重名！")
          return
        }
      }
      this.file.push(res?.data)

      this.$refs.upload.clearFiles() //上传成功之后清除历史记录

    },


    // 上传文件之前的钩子
    handleBeforeUpload(file) {
      // if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type ===
      //     'image/jpeg')) {
      //   this.$notify.warning({
      //     title: '警告',
      //     message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
      //   })
      // }
      // let size = file.size / 1024 / 1024 / 2;
      // if (size > 35) {
      //   this.$notify.warning({
      //     title: '警告',
      //     message: '图片大小必须小于35M'
      //   })
      // }

    },

    // 还可以输入多少个字
    remainder() {
      return this.maxLength - this.context.length
    },
    // 鼠标悬浮切换
    mouseover() {
      this.cDisplay = 'display: block '
    },
    mouseleave() {
      this.cDisplay = 'display: none '
    }
  }
}
</script>

<style scoped>


div {
  margin: 0;
  padding: 0;
  border: 0;
  display: block;
  unicode-bidi: isolate;
}

.content-container {
  width: 1020px !important;
  position: relative;
  margin: 70px auto 0;
  background: #fff;
}

.pull-left {
  float: left !important;
}
.file-action {
  float: left;
  font-size: 12px;
  color: #8d77fb;
  position: relative;
  line-height: 22px;
}


.file-action span {
  margin-right: 10px;

}

.input-text {
  border-top: 8px #ea5947 solid;
  border-radius: 4px;
  padding: 10px 10px;
}

.tip {
  float: right;
}

.tip span {
  font-size: 12px;
  color: #969696;
}


.button {
  margin-top: 10px;
  background-color: white;
  color: #444444;
  border: 1px #969696 solid;
}

.button:hover {
  border: 1px #529fff solid;
}

.file-attachwarp {
  border: 0;
  padding: 10px 0;
  zoom: 1;
  border-radius: 4px;
  cursor: pointer;
}

.file-info {
  cursor: pointer;
  overflow: hidden;
}
.image-wrap {
  width: 42px;
  height: 42px;
  line-height: 52px;
  overflow: hidden;
  float: left;
  margin-right: 5px;
}
.file-filetype {
  font-size: 37px!important;
  float: left;
  margin-right: 10px;
  color: #529fff;
  display: inline-block;
}

.file-attachmain {
  float: left;
  padding-right: 20px;
  max-width: 300px;
}
img {
  max-width: 100%;
  height: auto;
  background-size: 100% 100%;
}
.name {
  margin-top: 0;
  font-size: 14px;
  line-height: 22px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 5px;
}

.size {
  margin-top: 0;
  margin-bottom: 0;
  color: #969696;
}

.avatar-container {
  margin-top: 10px;
  width: 60%;
}


.iconfont {
  margin-right: 5px;
  font-size: 16px;
}

.button-red-solid {
  color: white;
  background-color: #ea5947;
  border: 1px #ea5947 solid;
}

.button-red-solid:hover {
  background-color: rgba(233, 56, 34, 0.68);
  border: 1px #ea5947 solid;
}


</style>